<template>
    <div class="account-box">
        <el-form
            ref="ruleFormRef"
            :model="loginForm"
            status-icon
            :rules="rules"
            label-width="60px"
            class="demo-ruleForm"
        >
            <el-form-item label="账号：" prop="account">
                <el-input v-model="loginForm.account" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
                <el-input v-model="loginForm.password" type="password" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
                <el-input v-model.number="loginForm.code" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref,reactive } from 'vue'
const ruleFormRef = ref()
const loginForm = reactive({
    account: '',
    password: '',
    code: '',
})
const checkCode = (ruley, value, callback) => {
    if (!value) {
        return callback(new Error('请输入有效的验证码'))
    }
    setTimeout(() => {
        if (!Number.isInteger(value)) {
            callback(new Error('验证码格式错误,请重新输入'))
        }
        callback()
    }, 500)
}
const validateAccount = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入有效的账号'))
    } else {
        if (loginForm.password !== '') {
            if (!ruleFormRef.value) return ruleFormRef.value.validateField('password', () => null)
        }
        callback()
    }
}
const validatePassword = (rule, value, callback) => {
  if (value === '') {
        callback(new Error('请输入有效的密码'))
  } else if (value !== loginForm.password) {
        callback(new Error("Two inputs don't match!"))
  } else {
        callback()
  }
}

const rules = reactive({
    account: [{ validator: validateAccount, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
    code: [{ validator: checkCode, trigger: 'blur' }]
})

const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            ElMessage.success('suscerer')
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>

<style lang="less" scoped>
.account-box{
    width: 100%;
    height: 100%;
    margin-top: 20px;
    .demo-ruleForm{
        margin-top: 20px;
        .el-input{
            width: 90%;
        }
    }
}
</style>